package asapIs134CK.womi.server.event;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import asapIs134CK.womi.client.event.RCPEventService;
import asapIs134CK.womi.client.event.WomiEvent;
import asapIs134CK.womi.client.profile.UserClient;
import asapIs134CK.womi.server.EMF;
import asapIs134CK.womi.server.profile.UserServer;

public class RPCEventServiceImpl extends RemoteServiceServlet implements RCPEventService{

	@Override
	public boolean addEvent(WomiEvent event) {
		boolean res = false;
    	HttpServletRequest request = this.getThreadLocalRequest();
    	HttpSession session = request.getSession();
    	Object o = session.getAttribute("UserWomi");
    	// On n'autorise pas la génération d'event par un utilisateur anonyme.
    	// On ne devrait pas faire d'appelle sur un utilisateur non loggé
		if(o != null){
			event.setUserEmail(((UserClient)o).getEmail());
			WomiEventServer eventServer = new WomiEventServer(event);
		    EntityManager em = EMF.get().createEntityManager();
		    try {
		        em.persist(eventServer);
		        res = true;
		    } finally {
		        em.close();
		    }
		}
		return res;
	}

	@Override
	public List<WomiEvent> getEvents() {
		List<WomiEventServer> tmp = null;
		List<WomiEvent> res = null;
	    EntityManager em = EMF.get().createEntityManager();
	    try {
	    	Query query = em.createQuery("SELECT e FROM WomiEventServer e ORDER BY e._date descending");
	    	query.setMaxResults(10);
	    	tmp = query.getResultList();
	    	Iterator<WomiEventServer> ite = tmp.iterator();
	    	res = new ArrayList<WomiEvent>();
	    	while(ite.hasNext()){
	    		WomiEventServer o = ite.next();
	    		WomiEvent e = new WomiEvent(o.getDate(), o.getMessage());
	    		e.setUserEmail(o.getUserEmail());
	    		res.add(e);
	    	}
	    } finally {
	        em.close();
	    }
		return res;
	}

}
